﻿using KAKA.Domain;
using KAKA.Repository;
using Morus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KAKA
{
    public class EmailVerificationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public EmailVerificationAttribute()
            : this(new string[] { })
        {
        }

        public EmailVerificationAttribute(string[] excludeActionName)
        {
            Order = 3;
            ExcludeActionName = excludeActionName;
        }

        public string[] ExcludeActionName { get; set; }

        protected virtual void HandleEmailVerifyFailedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new EmailUnverifiedResult();
        }

        private bool IsUnverifyEmailAction(AuthorizationContext filterContext)
        {
            return ExcludeActionName.Contains(filterContext.ActionDescriptor.ActionName) &&
            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "Personal";
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.HttpContext;

            if (httpContext.User.Identity.IsAuthenticated)
            {
                if (IsUnverifyEmailAction(filterContext) == false)
                {
                    var user = WebUtil.GetCurrentUser();

                    if (user.EmailVerified == false)
                    {
                        HandleEmailVerifyFailedRequest(filterContext);
                    }
                }
            }
        }
    }
}